package com.citrix.gs.kit;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommonKit {

    private static Logger logger = LoggerFactory.getLogger(CommonKit.class);
            
    public static String readStreamContent(InputStream is) throws IOException {
        
        InputStreamReader isr = new InputStreamReader(is);
        
        int n2;
        char[] c2 = new char[1024];
        StringBuffer content = new StringBuffer();
        while ((n2 = isr.read(c2)) > 0) {
            content.append(c2, 0, n2);
        }
        
        return  content.toString();
    }
    
    public static String runCmd(String cmdString) {
        try {
            
            Runtime runTime = Runtime.getRuntime();
            
            Process process = runTime.exec(cmdString);
            
            String processError = readStreamContent(process.getErrorStream());
            if(processError.isEmpty()) {
                return "Output: \n" + readStreamContent(process.getInputStream()); 
            } else {
                return "Error: \n" + processError;
            }
            
        } catch (IOException e) {
            logger.error("Exception: ", e);
            return "Error: " + e.getMessage(); 
        }
          
    }
    
    public static boolean waitForInput(String prompt){
        
        while(true){
            System.out.println(prompt);
            System.out.println("Please input Y/N[yes/no]:");
            try {
                String inStr = "";
                while(true) {
                    int ret = System.in.read();
                    //System.out.println(":" + ret);
                    if(ret == -1 || ret == 10 || ret == 13) {
                        break;
                    } else {
                       inStr += (char)ret; 
                    }
                }

                if(inStr.equalsIgnoreCase("y") || inStr.equalsIgnoreCase("yes")) {
                    return true;
                } else if(inStr.equalsIgnoreCase("n") || inStr.equalsIgnoreCase("no")){
                    return false;
                } else {
                  System.out.println("Invalid input is: " + inStr);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
